var sysFormly = angular.module('formlySystem', [
    'formly', 'formlyBootstrap', 'ui.bootstrap',
    'ngSanitize', 'ui.select', 'ui.grid'
]);
app.requires.push('formlySystem');
// var appFormly = angular.module('formlyExample', [
//     'formly', 'formlyBootstrap','ui.bootstrap',
//     'ngSanitize','ui.select','ui.grid'],

sysFormly.config(
    function config(formlyConfigProvider) {
        //格式转换方法 XXX-XXX转驼峰命名
    });



sysFormly.controller('SystemformCtrl', ['$rootScope', '$scope', '$parse', '$filter', '$injector', '$http', '$q', '$state', '$stateParams', '$modal', '$timeout', '$interval', 'SweetAlert', 'FileUploader', 'i18nService', 'moment', 'Restangular', 'UserRestangular', 'BpmRestangular', 'api_configure_form', 'api_bpm_domain', 'api_bpm_data', 'api_user_data',
    function($rootScope, $scope, $parse, $filter, $injector, $http, $q, $state, $stateParams, $modal, $timeout, $interval, SweetAlert, FileUploader, i18nService, moment, Restangular, UserRestangular, BpmRestangular, api_configure_form, api_bpm_domain, api_bpm_data, api_user_data) {

        //console.log($stateParams);
        var vm = this;
        vm.options = {};
        vm.exampleTitle = ['expressionProperties', 'model property'];
        vm.fields = [];
        vm.model = {};

        $scope.langs = i18nService.getAllLangs();
        $scope.lang = 'zh-cn';
        //alert($rootScope.user.id,null,2);
        vm.model["loginUser"] = $rootScope.user;
        var that = $injector;
        var parse = $parse;

        var modelWatch = "";
        var fieldsWatch = [];
        var serviceWatch = null;
        var formWatch = {};
        if (angular.isDefined($stateParams.model) && $stateParams.model != "") {
            modelWatch = JSON.parse($stateParams.model);
            // console.log("modelWatch:"+ JSON.stringify(modelWatch));
        }
        if (angular.isDefined($stateParams.fields) && $stateParams.fields != "") {
            fieldsWatch = JSON.parse($stateParams.fields);
        }
        if (angular.isDefined($stateParams.extjson) && $stateParams.extjson != "") {
            formWatch.extjson = JSON.parse($stateParams.extjson);
        }
        if (angular.isDefined($stateParams.cancelUrl) && $stateParams.cancelUrl != "") {
            formWatch.cancelUrl = $stateParams.cancelUrl;
        }
        if (angular.isDefined($stateParams.url) && $stateParams.url != "") {
            formWatch.url = $stateParams.url;
        }
        if (angular.isDefined($stateParams.service) && $stateParams.service != "") {
            if (that.has($stateParams.service)) {
                serviceWatch = that.get($stateParams.service);
            } else {
                serviceWatch = $stateParams.service;
            }
        }

        //用户测试数据，后续从header的auth中获取
        var userId = 2;
        userId = $rootScope.user.id;

        //==============处理表单设计数据  开始====================
        //处理组件加载后台数据选项的方法
        function refreshSelectOptions(searchVal, field) {
            //todo
            console.log(field);
            if (field.key == 'id' && field.templateOptions.pkey == 'change.source') {
                field.templateOptions.options = [{ "id": 1, "name": "事件", "code": 1 }, { "id": 2, "name": "问题", "code": 2 }, { "id": 3, "name": "配置", "code": 3 }, { "id": 4, "name": "服务级别", "code": 4 }, { "id": 5, "name": "内部需求", "code": 5 }];
            } else if (field.templateOptions.optionsUrl) {
                var process = BpmRestangular.all("");
                if (field.templateOptions.ApiService) {
                    process = UserRestangular.all("");
                }

                process.customPOST({ "idx": 0, "sum": 1000 }, field.templateOptions.optionsUrl).then(function(result) {
                    if (!field.templateOptions.options) {
                        field.templateOptions.options = [];
                    }
                    if (field.templateOptions.optionsDataKey) {
                        field.templateOptions.options = result[field.templateOptions.optionsDataKey];
                    } else {
                        field.templateOptions.options = result;
                    }
                });
            }
        }



        //解析自定义表单设计数据
        function decodeVMForm(vmForm) {
            var result = { model: {}, fields: [] };
            //设置模型实体数据 begin
            //        var mdata = vmForm.model;
            //解析数据实体
            var mdata = angular.fromJson(vmForm.model); //JSON.parse(field.extjson);
            angular.extend(result.model, mdata);

            if (modelWatch != null && modelWatch != '') {
                //angular.extend(result.model.incident,modelWatch.incident);
                //result.model.alarmType = modelWatch.alarmType;
                // vmForm.cancelUrl = modelWatch.cancelUrl;
                for (var index in modelWatch.model) {
                    console.log(JSON.stringify(index + " " + JSON.stringify(modelWatch.model[index])));
                    if (result.model[index] != null) {
                        angular.extend(result.model[index], modelWatch.model[index]);
                    } else {
                        result.model[index] = modelWatch.model[index];
                    }
                }
            }
            //设置模型实体数据 end
            //解析设计数据生成表单项 begin
            var fields = [];
            //处理修改设计数据中展示设置
            angular.forEach(vmForm.fields, function(field) {
                if (field.key == "") {
                    delete field.key;
                }

                if (angular.isDefined(field.extjson)) {
                    var extObj = angular.fromJson(field.extjson); //JSON.parse(field.extjson);
                    angular.extend(field.templateOptions, extObj.templateOptions);
                    delete extObj.templateOptions;
                    for (var prop in extObj) {
                        if (new RegExp("Expression").test(prop)) {
                            //var obj = $scope.$eval(extObj[prop]);
                            //extObj[prop] = $scope.$eval(extObj[prop]);
                            if (extObj[prop] != null) {
                                if (new RegExp("function").test(extObj[prop])) {
                                    var propValue = eval(extObj[prop]);
                                    extObj[prop] = propValue;
                                } else {
                                    //console.log(extObj[prop]);
                                    var obj = $scope.$eval(extObj[prop]);
                                    extObj[prop] = obj;
                                    //console.log(obj);
                                }
                            }
                        } else if (new RegExp("expressionProperties").test(prop)) {
                            for (var p in extObj[prop]) {
                                if (new RegExp("function").test(extObj[prop][p])) {
                                    var propValue = eval(extObj[prop][p]);
                                    extObj[prop][p] = propValue;
                                } else {

                                }
                            }
                        } else if ("watcher" == prop) {
                            if (angular.isArray(extObj[prop])) {
                                angular.forEach(extObj[prop], function(item, index) {
                                    for (var p in item) {
                                        if (new RegExp("function").test(item[p])) {
                                            var propValue = eval(item[p]);
                                            extObj[prop][index][p] = propValue;
                                        }
                                    }
                                });
                            } else if (angular.isObject(extObj[prop])) {
                                for (var p in extObj[prop]) {
                                    if (new RegExp("function").test(extObj[prop][p])) {
                                        var propValue = eval(extObj[prop][p]);
                                        extObj[prop][p] = propValue;
                                    }
                                }
                            }
                        }
                    }
                    angular.extend(field, extObj);
                    delete field.extjson;
                }


                if (angular.isDefined(field.templateOptions)) {
                    var templateOs = field.templateOptions;
                    for (var property in templateOs) {
                        //console.log(property);
                        if (angular.isString(templateOs[property]) && !(new RegExp("[\u4e00-\u9fa5]").test(templateOs[property]))) {
                            if (new RegExp("function").test(templateOs[property])) {
                                var propValue = eval(templateOs[property]);
                                field.templateOptions[property] = propValue;
                            } else {
                                if (that.has(templateOs[property])) {
                                    field.templateOptions[property] = that.get(templateOs[property]);
                                } else {
                                    field.templateOptions[property] = templateOs[property];
                                }
                            }
                        } else if (templateOs[property] == null) {
                            //delete field.templateOptions[property];
                        } else {}
                    }
                }
                //console.log(field);
                if (angular.isDefined(field.templateOptions) && angular.isDefined(field.templateOptions.extjson)) {
                    var extObj = angular.fromJson(field.templateOptions.extjson); //JSON.parse(field.extjson);
                    angular.extend(field.templateOptions, extObj);
                    delete field.templateOptions.extjson;
                }
                //...
                if (field.templateOptions) {
                    //处理远程获取数据控件方法调用
                    if (field.templateOptions.optionsUrl) {
                        field.templateOptions.refresh = refreshSelectOptions;
                    }
                    //处理嵌套属性数据绑定/
                    if (field.templateOptions.pkey) {
                        var pmodel, i = 0;
                        angular.forEach(field.templateOptions.pkey.split("."), function(p) {
                            if (i == 0) {
                                if (result.model[p] == null) {
                                    result.model[p] = {};
                                }
                                pmodel = result.model[p];
                                i++;
                            } else {
                                if (pmodel[p] == null) {
                                    pmodel[p] = {};
                                }
                                pmodel = pmodel[p];
                            }
                        });
                        if (pmodel != null) {
                            field.model = pmodel;
                            if (pmodel[field.key] == null) {
                                pmodel[field.key] = null;
                            }
                        }
                    } else {
                        if (result.model[field.key] == null) {
                            result.model[field.key] = null;
                        }
                    }
                    //处理弹出框组件初始化
                    if (field.type == "ui-input-selectmodal") {
                        field.templateOptions.modal = $modal;
                        //field.templateOptions.Restangular = Restangular;
                    } else if (field.type == "ui-requesterselect") {
                        //field.templateOptions.language = $scope.lang;
                        field.templateOptions.modal = $modal;
                        field.templateOptions.UserService = api_user_data;
                    } else if (field.type == "ui-userselect") {
                        field.templateOptions.modal = $modal;
                        //field.templateOptions.Restangular = Restangular;
                    } else if (field.type == "ui-multiuserselect") {
                        field.templateOptions.modal = $modal;
                    } else if (field.type == "ui-search") {
                        field.templateOptions.modal = $modal;
                    } else if (field.type == "ui-modelselect") {
                        field.templateOptions.modal = $modal;
                        //console.log("$rootScope.user:" + JSON.stringify($rootScope.user));
                        field.templateOptions.loginUser = $rootScope.user;
                        //field.templateOptions.Restangular = Restangular;
                    } else if (field.type == "ui-dropfile") {
                        $scope.fileUploader = field.templateOptions.fileUploader = new FileUploader({
                            url: '/uploader'
                        });
                        field.templateOptions.taskId = $stateParams.taskId;
                        field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                        field.templateOptions.userId = $rootScope.user.id;
                        //field.ApiService=api_bpm_domain;
                    } else if (field.type == "ui-dropfiletable") {
                        if (field.templateOptions.processInstanceId) {

                        } else {
                            field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                        }
                    } else if (field.type == "ui-repeatSection") {
                        var repeatForm = {
                            model: {

                            },
                            fields: field.templateOptions.fields
                        };
                        repeatForm.model[field.key] = [];
                        decodeVMForm(repeatForm);
                    } else if (field.type == "ui-currentuser") {
                        field.templateOptions.user = vm.model["loginUser"];
                    }
                }

                //          console.log(field);
                result.fields.push(field);
            });
            angular.extend($scope.vm.fields, result.fields);
            angular.extend($scope.vm.model, result.model);
            console.log($rootScope.user);
            //vm.model["loginUser"] = $rootScope.user;
            if (modelWatch != null && modelWatch != '' && modelWatch.cancelUrl != null && modelWatch.cancelUrl != '') {
                vmForm.cancelUrl = modelWatch.cancelUrl;
            }
            $scope.formData = vmForm;
            //console.log($scope.vm);

            //解析设计数据生成表单项 end
            return result;
        }
        //======================处理表单设计数据  结束========================
        $scope.ldloading = {};

        function filter(obj) {
            angular.forEach(obj, function(key, value) {
                if (value === "" || value === null) {
                    delete obj[key];
                } else if (Object.prototype.toString.call(value) === '[object Object]') {
                    filter(value);
                } else if (angular.isArray(value)) {
                    angular.forEach(value, function(item) {
                        filter(item);
                    });
                }
            });
        }


        $scope.closeModel = function() {
            // console.log("$stateParams.formKey="+JSON.stringify($stateParams.formKey))
            if (angular.isDefined($stateParams.formKey) && $stateParams.formKey != "") {
                if ($stateParams.formKey == "system_edit") {
                    $rootScope.cmdbs = "user";
                    $state.go('app.system.user.user', {});
                } else if ($stateParams.formKey == "system_edit_role") {
                    $rootScope.cmdbs = "role";
                    $state.go('app.system.user.role', {});
                } else if ($stateParams.formKey == "system_edit_navmanager") {
                    $rootScope.cmdbs = "nav";
                    $state.go('app.system.navmanager', {});
                }
                event.preventDefault();
            }
        }
        $scope.keyup = function(e) {
            // lastKeyDown = -1;
            if (e.keyCode === 32) {
                event.preventDefault();
            }
        }
        vm.submit = function(data, style) {
            $rootScope.cmdbs = "false";
            console.log("data=" + JSON.stringify(data));
            if ($stateParams.formKey == "system_edit") {
                $scope.roleid = "";
                for (var i = 0; i < data.user.role.length; i++) {
                    if (angular.isDefined(data.user.role[i]) && data.user.role[i].id == 2) {
                        $scope.roleid = "true";
                        break;
                    } else { $scope.roleid = "false"; }
                }
                // console.log("roleid="+$scope.roleid);
                if (vm.form.$valid && $scope.roleid == "true") {
                    vm.options.updateInitialValue();
                    $scope.ldloading[style.replace('-', '_')] = true;
                    //        alert(JSON.stringify(vm.model), null, 2);
                    var _ = window._;
                    vm.model = (function filter(obj) {
                        var dateTransKeys = [];
                        var filtered = _.pick(obj, function(v, k, obj) {
                            if (_.isDate(v)) {
                                dateTransKeys.push(k);
                            }
                            return angular.isDefined(v) && v !== null && (angular.isArray(v) ? v.length > 0 : true) && (_.isPlainObject(v) ? (!_.isEmpty(v)) : true);
                        });

                        return _.cloneDeep(filtered, function(v, index, object) {
                            if (angular.isArray(dateTransKeys) && dateTransKeys.length > 0) {
                                angular.forEach(dateTransKeys, function(item) {
                                    v[item] = moment(v[item]).format('YYYY-MM-DD HH:mm:ss');
                                });
                                dateTransKey = [];
                                return v;
                            }
                            return !(_.isEmpty(filtered)) && v !== filtered && _.isPlainObject(v) ? filter(v) : undefined;
                        });
                    })(vm.model);

                    console.log("$scope.formData=" + $scope.formData);
                    switch ($scope.formData.url) {
                        case "create":
                            //vm.model["initUser"]=$rootScope.user.id;                        
                            //addData
                            serviceWatch.addData($scope.formData.modelName, vm.model).then(function(response) {
                                if (response) {
                                    var resData = Restangular.stripRestangular(response);
                                    if (resData && resData.status == 200) {
                                        SweetAlert.swal({
                                            title: "提交成功!",
                                            confirmButtonColor: "#007AFF"
                                        }, function() {
                                            $state.go($scope.formData.cancelUrl);
                                        });
                                    } else {
                                        SweetAlert.swal({
                                            title: "系统错误",
                                            text: "系统错误，请稍后重试!",
                                            type: "error",
                                            confirmButtonColor: "#DD6B55"
                                        });
                                    }
                                } else {
                                    SweetAlert.swal({
                                        title: "系统错误",
                                        text: "系统错误，请稍后重试!",
                                        type: "error",
                                        confirmButtonColor: "#DD6B55"
                                    });
                                }
                                $scope.ldloading[style.replace('-', '_')] = false;
                            });
                            break;
                        case "save":
                            //addData
                            serviceWatch.addData($scope.formData.modelName, vm.model).then(function(response) {
                                if (response) {
                                    var resData = Restangular.stripRestangular(response);
                                    modelWatch.model

                                    // console.log("resData="+JSON.stringify(resData.data.role[0].id));

                                    if (resData && resData.status == 200) {
                                        SweetAlert.swal({
                                            title: "提交成功!",
                                            confirmButtonColor: "#007AFF"
                                        }, function() {

                                            $state.go($scope.formData.cancelUrl);
                                        });
                                    } else {
                                        SweetAlert.swal({
                                            title: "系统错误",
                                            text: "系统错误，请稍后重试!",
                                            type: "error",
                                            confirmButtonColor: "#DD6B55"
                                        });
                                    }
                                } else {
                                    SweetAlert.swal({
                                        title: "系统错误",
                                        text: "系统错误，请稍后重试!",
                                        type: "error",
                                        confirmButtonColor: "#DD6B55"
                                    });

                                }
                                $scope.ldloading[style.replace('-', '_')] = false;
                            });
                            break;
                        case "close":
                            $state.go($scope.formData.cancelUrl);
                            break;
                        default:
                            $scope.ldloading[style.replace('-', '_')] = false;
                            break;
                    }
                } else if ($scope.roleid != "true") {
                    SweetAlert.swal({
                        title: "角色设置错误",
                        text: "请填写必填项!",
                        type: "error",
                        confirmButtonColor: "#DD6B55"
                    });
                } else {
                    SweetAlert.swal({
                        title: "校验错误",
                        text: "请填写必填项!",
                        type: "error",
                        confirmButtonColor: "#DD6B55"
                    });
                    angular.forEach(vm.form.$error.required, function(item) {
                        angular.forEach(vm.fields, function(f) {
                            if (f.name == item.$name) {
                                f.validation.show = true;
                            }
                        });
                    })
                }
            } else {
                var role = {};
                var data1 = {};
                console.log("data.role=" + JSON.stringify(data.role));
                role['rolecode'] = data.role.rolecode;
                role['id'] = data.role.id;
                console.log("role=" + JSON.stringify(role));
                data1['role'] = role;
                console.log("data1=" + JSON.stringify(data1));
                api_user_data.validate(data1, 'role').then(function(response) {
                    var resData = Restangular.stripRestangular(response);
                    console.log("resData11=" + JSON.stringify(resData));
                    if (resData.status == 200 && resData.data == "false" && vm.form.$valid) {

                        // if (vm.form.$valid ) {
                        vm.options.updateInitialValue();
                        $scope.ldloading[style.replace('-', '_')] = true;
                        // alert(JSON.stringify(vm.model), null, 2);

                        var _ = window._;
                        vm.model = (function filter(obj) {
                            var dateTransKeys = [];
                            var filtered = _.pick(obj, function(v, k, obj) {
                                if (_.isDate(v)) {
                                    dateTransKeys.push(k);
                                }
                                return angular.isDefined(v) && v !== null && (angular.isArray(v) ? v.length > 0 : true) && (_.isPlainObject(v) ? (!_.isEmpty(v)) : true);
                            });

                            return _.cloneDeep(filtered, function(v, index, object) {
                                if (angular.isArray(dateTransKeys) && dateTransKeys.length > 0) {
                                    angular.forEach(dateTransKeys, function(item) {
                                        v[item] = moment(v[item]).format('YYYY-MM-DD HH:mm:ss');
                                    });
                                    dateTransKey = [];
                                    return v;
                                }
                                return !(_.isEmpty(filtered)) && v !== filtered && _.isPlainObject(v) ? filter(v) : undefined;
                            });
                        })(vm.model);

                        // console.log("$scope.formData="+$scope.formData);  
                        switch ($scope.formData.url) {
                            case "create":
                                //vm.model["initUser"]=$rootScope.user.id;                        
                                //addData
                                serviceWatch.addData($scope.formData.modelName, vm.model).then(function(response) {
                                    if (response) {
                                        var resData = Restangular.stripRestangular(response);
                                        if (resData && resData.status == 200) {
                                            SweetAlert.swal({
                                                title: "提交成功!",
                                                confirmButtonColor: "#007AFF"
                                            }, function() {
                                                $state.go($scope.formData.cancelUrl);
                                            });
                                        } else {
                                            SweetAlert.swal({
                                                title: "系统错误",
                                                text: "系统错误，请稍后重试!",
                                                type: "error",
                                                confirmButtonColor: "#DD6B55"
                                            });
                                        }
                                    } else {
                                        SweetAlert.swal({
                                            title: "系统错误",
                                            text: "系统错误，请稍后重试!",
                                            type: "error",
                                            confirmButtonColor: "#DD6B55"
                                        });
                                    }
                                    $scope.ldloading[style.replace('-', '_')] = false;
                                });
                                break;
                            case "save":
                                //addData
                                serviceWatch.addData($scope.formData.modelName, vm.model).then(function(response) {
                                    if (response) {
                                        var resData = Restangular.stripRestangular(response);
                                        // console.log("resData="+JSON.stringify(resData.data));
                                        // console.log("modelWatch.model="+JSON.stringify(modelWatch.model));
                                        if (resData && resData.status == 200) {
                                            SweetAlert.swal({
                                                title: "提交成功!",
                                                confirmButtonColor: "#007AFF"
                                            }, function() {

                                                $state.go($scope.formData.cancelUrl);
                                            });
                                        } else {
                                            SweetAlert.swal({
                                                title: "系统错误",
                                                text: "系统错误，请稍后重试!",
                                                type: "error",
                                                confirmButtonColor: "#DD6B55"
                                            });
                                        }
                                    } else {
                                        SweetAlert.swal({
                                            title: "系统错误",
                                            text: "系统错误，请稍后重试!",
                                            type: "error",
                                            confirmButtonColor: "#DD6B55"
                                        });

                                    }
                                    $scope.ldloading[style.replace('-', '_')] = false;
                                });
                                break;
                            case "close":
                                $state.go($scope.formData.cancelUrl);
                                break;
                            default:
                                $scope.ldloading[style.replace('-', '_')] = false;
                                break;
                        }
                    } else if (resData.status == 200 && resData.data == "true" && vm.form.$valid) {
                        SweetAlert.swal({
                            title: "角色代码以存在",
                            text: "请重新填写角色代码!",
                            type: "error",
                            confirmButtonColor: "#DD6B55"
                        });
                    } else {
                        SweetAlert.swal({
                            title: "校验错误",
                            text: "请填写必填项!",
                            type: "error",
                            confirmButtonColor: "#DD6B55"
                        });
                        angular.forEach(vm.form.$error.required, function(item) {
                            angular.forEach(vm.fields, function(f) {
                                if (f.name == item.$name) {
                                    f.validation.show = true;
                                }
                            });
                        })
                    }
                })
            }
        };


        $scope.vm = vm;



        if (angular.isDefined($stateParams.formKey) && $stateParams.formKey != "") {
            api_configure_form.renderForm($stateParams.formKey, '00000').then(function(responseData) {
                if (responseData) {
                    //console.log("responseData>>>");console.log(responseData);
                    var vmForm = Restangular.stripRestangular(responseData);
                    if (vmForm) {
                        //console.log("vmForm>>>");console.log(vmForm);
                        var modelData = {};
                        //modelData=myData.data;

                        decodeVMForm(vmForm);

                    }
                }
            });
        } else {
            // 
            if (angular.isDefined(fieldsWatch) && fieldsWatch.length > 0) {
                var vmForm = {
                    fields: fieldsWatch,
                    model: modelWatch
                }
                angular.extend(vmForm, formWatch);
                //$scope.formData = vmForm;
                if (vmForm) {
                    decodeVMForm(vmForm);
                }
            } else { //for form
                //TODO
                //测试数据 开始
                var testJson = {
                    fields: [{
                            key: 'formtitle',
                            type: 'ui-title',
                            noFormControl: true,
                            templateOptions: {
                                label: 'title is ',
                                placeholder: 'Formly is terrific!'
                            }
                        },
                        {
                            key: 'b',
                            type: 'ui-input',
                            className: 'col-xs-4',
                            templateOptions: {
                                type: 'input',
                                label: 'input a',
                                placeholder: 'search a...',
                                rBtn: {
                                    icon: 'fa fa-phone',
                                    onClick: function(val, opt, el, ev, model) { alert(val); }
                                },
                                lAddon: '<i class="fa fa-phone"/>'
                            }
                        },
                        {
                            key: 'id',
                            type: 'ui-select',
                            //initialValue:"false",
                            templateOptions: {
                                label: "测试默认值",
                                optionsUrl: "abc",
                                //options:[{"id":"false","name":"不取消"},{"id":"true","name":"取消"}],
                                // refresh:function(){
                                //     return [{"id":1,"name":"事件","code":1},{"id":2,"name":"问题","code":2},{"id":3,"name":"配置","code":3},{"id":4,"name":"服务级别","code":4},{"id":5,"name":"内部需求","code":5}];
                                // },  
                                //options:[{"id":1,"name":"事件","code":1},{"id":2,"name":"问题","code":2},{"id":3,"name":"配置","code":3},{"id":4,"name":"服务级别","code":4},{"id":5,"name":"内部需求","code":5}],
                                valueProp: "id",
                                labelProp: "name",
                                pkey: "change.source"
                            }
                        },
                        {
                            key: 'systemType',
                            type: 'ui-multiselect',
                            className: 'col-xs-4',
                            templateOptions: {
                                label: "所属系统类型",
                                pkey: "change",
                                valueProp: "id",
                                labelProp: "source",
                                optionsUrl: "data/fetchDataList/changesystemtype",
                                optionsDataKey: "list",
                                onChange: function(value, options, that, event, model) {
                                    var field = null;
                                    angular.forEach(that.$parent.fields, function(item) {
                                        if (item.key == 'influenceDepartment') {
                                            field = item;
                                        }
                                        if (item.key == 'notificationDepartment') {
                                            notifyField = item;
                                        }
                                    })
                                    if (field != null) {
                                        field.templateOptions.optionsPostData = {
                                            'systemIds': []
                                        }
                                        angular.forEach(value, function(vue) {
                                            field.templateOptions.optionsPostData['systemIds'].push({ 'id': vue });
                                        })
                                        field.value([]);
                                        if (value.length > 0) {
                                            field.templateOptions.refreshData(null, field);
                                        }
                                    }
                                    if (notifyField != null) {
                                        notifyField.templateOptions.optionsPostData = {
                                            'systemIds': []
                                        }
                                        angular.forEach(value, function(vue) {
                                            notifyField.templateOptions.optionsPostData['systemIds'].push({ 'id': vue });
                                        })
                                        notifyField.value([]);
                                        if (value.length > 0) {
                                            notifyField.templateOptions.refreshData(null, notifyField);
                                        }
                                    }


                                }
                            }
                        },
                        {
                            key: 'influenceDepartment',
                            type: 'ui-multiselectplus',
                            className: 'col-xs-4',
                            templateOptions: {
                                label: '所影响的应用系统、部门',
                                pkey: "change",
                                valueProp: '', //对应value
                                labelProp: 'dept', //对应key
                                optionsUrl: 'dept/findBySystemType', //对应后台地址，api/之前的部分省略
                                optionsDataKey: 'list', //对应返回数组数据的键值,
                                optionsPostData: function(options, model, scope) {
                                    return { "systemIds": [] };
                                },
                                refreshData: function(search, options, model, that) {

                                    options.templateOptions.options = [{ "id": 13, "dept": "村镇银行管理部" }, { "id": 14, "dept": "电子银行部" }];

                                    options.value(options.templateOptions.options);
                                },
                                optionsChecked: true,
                                required: true,
                                ApiService: UserRestangular

                            }
                        },
                        {
                            key: 'notificationDepartment',
                            type: 'ui-multiselectplus',
                            className: 'col-xs-4',
                            templateOptions: {
                                label: '需通知部门',
                                pkey: "change",
                                valueProp: 'id', //对应value
                                labelProp: 'dept', //对应key
                                optionsUrl: 'dept/findBySystemType', //对应后台地址，api/之前的部分省略
                                optionsDataKey: 'list', //对应返回数组数据的键值,
                                optionsPostData: function(options, model, scope) {
                                    return { "systemIds": [] };
                                },
                                optionsChecked: true,
                                required: true,
                                ApiService: UserRestangular
                            }
                        },
                        {
                            type: 'ui-label',
                            key: 'arrayData',
                            className: 'col-xs-4',
                            templateOptions: {
                                label: '数组label数据',
                                labelProp: 'dept'
                            }
                        },
                        {
                            key: 'selectUser',
                            type: 'ui-requesterselect',
                            className: 'col-xs-12',
                            templateOptions: {
                                label: '请求人信息',
                                modalTitle: '请求人列表',
                                fetchItems: function(filterData, APIService) {
                                    return APIService.fetchDataList('requester', filterData);
                                },
                                Restangular: Restangular,
                                ApiService: api_user_data
                                    // onClick:function(val, options, field, event , model){
                                    //     console.log(options);
                                    // }
                            }
                        },
                        {
                            key: 'cabUser',
                            type: 'ui-multiuserselect',
                            className: 'col-xs-12',
                            templateOptions: {
                                label: 'CAB评审成员',
                                modalTitle: 'CAB成员列表',
                                fetchItems: function(filterData, APIService) {
                                    return APIService.fetchDataList('user', filterData);
                                },
                                Restangular: Restangular,
                                ApiService: api_user_data,
                                onClick: function(val, options, field, event, model) {
                                    console.log(model);
                                }
                            }
                        },

                        // {
                        //     key:'incident',
                        //     type:'ui-modelselect',
                        //     className:'col-xs-3',
                        //     templateOptions:{
                        //         label:'关联事件工单',
                        //         modalTitle:'事件列表',
                        //         fetchItems:function(filterData,APIService){
                        //             return APIService.fetchDataList('incident',filterData);
                        //         },
                        //         Restangular:"Restangular",
                        //         ApiService:"api_bpm_data",
                        //         columnDefs:[
                        //                     { name:'id', width:80, enableFiltering:false},
                        //                     { name:'title', displayName:'事件主题', width:140},
                        //                     { name:'type.name', displayName:'事件类型', width:140},
                        //                     { name:'emergency.name', displayName:'紧急度', width:80},
                        //                     { name:'state.name', displayName:'状态', width:100},
                        //                     { name:'emergency.name', displayName:'紧急度', width:80},
                        //                     { name:'influence.name', displayName:'影响度', width:80},
                        //                     { name:'priority.name', displayName:'优先级', width:80},
                        //                     { name:'handlerUser.name', displayName:'当前处理人', width:100},
                        //                     { name:'acceptDate', displayName:'创建时间', width:100}                                        
                        //         ],
                        //         displayName:'title', 
                        //         onClick:function(val, options, field, event , model){
                        //             //model.start_code++;
                        //             console.log(options);
                        //         }
                        //     }
                        // },
                        // {
                        //     key: 'worknumber',
                        //     type: 'ui-workernumber',
                        //     className:'col-xs-3',
                        //     templateOptions: {
                        //         label: 'work number',
                        //         Restangular:Restangular,
                        //         ApiService:api_bpm_domain,
                        //         getWorkernumber: function(APIService){
                        //             return APIService.workernumber('bg');
                        //         }
                        //     }
                        // },
                        // {
                        //     key: 'chkme',
                        //     type: 'ui-checkbox',
                        //     className:'col-xs-3',
                        //     templateOptions: {
                        //         label: 'Check me out'
                        //     }
                        // },
                        // {
                        //     key: 'droplink',
                        //     type: 'ui-link',
                        //     className: 'col-xs-3',
                        //     templateOptions:{
                        //         label:'添加附件',
                        //         onClick:function(val, options, field, event ,model){
                        //             if(angular.isUndefined(field.form.dropState)){
                        //                 field.form.dropState=false;
                        //             }
                        //             field.form.dropState=!field.form.dropState;  
                        //             console.log(field);
                        //         }
                        //     }
                        // },
                        // {
                        //     key: 'dropfile',
                        //     type: 'ui-dropfile',
                        //     className: 'col-xs-12',
                        //     templateOptions:{
                        //         label:'附件',
                        //         uploadUrl:'http://127.0.0.1:9008/saveAttachments'
                        //     }
                        // },
                        // {
                        //     type: 'ui-label',
                        //     key: 'changesign',
                        //     className: 'col-xs-4',
                        //     templateOptions: {
                        //         label:'变更请求单号',
                        //         pkey:'change'
                        //     }
                        // },
                        // {   
                        //     type: 'ui-label',
                        //     key: 'title',
                        //     className: 'col-xs-4',
                        //     templateOptions: {
                        //         label:'变更标题',
                        //         pkey:'change'
                        //     }
                        // },
                        // //关联发布单号
                        // //新建发布                    
                        // {
                        //     key: 'droplist',
                        //     type: 'ui-dropfiletable',
                        //     className: 'col-xs-12',
                        //     templateOptions:{
                        //         label:'附件下载列表',
                        //         Restangular:Restangular,
                        //         processInstanceId:'250033',
                        //         ApiService:api_bpm_domain
                        //     }
                        // },
                        // {
                        //     type: 'ui-repeatSection',
                        //     key: 'investments',
                        //     className: 'col-xs-12',
                        //     templateOptions: {
                        //         btnText: '新增变更施工单',
                        //         fields: [
                        //             {
                        //                 className: 'col-xs-3',
                        //                 type: 'ui-input',
                        //                 key: 'aboutci',
                        //                 templateOptions: {
                        //                     label: '关联的配置项',
                        //                     required: true
                        //                 }
                        //             },
                        //             {
                        //                 className: 'col-xs-3',
                        //                 type: 'ui-datepicker',
                        //                 key: 'planbegintime',
                        //                 templateOptions: {
                        //                     label: '计划开始时间',
                        //                     required: true
                        //                 }
                        //             },   
                        //             {
                        //                 className: 'col-xs-3',
                        //                 type: 'ui-datepicker',
                        //                 key: 'planendtime',
                        //                 templateOptions: {
                        //                     label: '计划完成时间',
                        //                     required: true
                        //                 }
                        //             },
                        //             {
                        //                 className: 'col-xs-12',
                        //                 type: 'ui-userselect',
                        //                 key: 'handleruser',
                        //                 templateOptions: {
                        //                     label: '实施人员信息',
                        //                     modalTitle:'实施人列表',
                        //                     required: true,
                        //                     fetchItems:function(filterData, APIService){
                        //                         return APIService.fetchDataList('user',filterData);
                        //                     },
                        //                     Restangular:Restangular,
                        //                     ApiService:api_user_data,
                        //                     onClick:function(val, options, field, event , model){
                        //                         //model.start_code++;
                        //                         console.log(options);
                        //                     }
                        //                 }
                        //             },
                        //             {
                        //                 className: 'col-xs-8',
                        //                 type: 'ui-textarea',
                        //                 key: 'handlerContent',
                        //                 templateOptions: {
                        //                     label: '实施内容',
                        //                     required: true,
                        //                     row:10
                        //                 }
                        //             },{
                        //                 noFormControl: true,
                        //                 template:'<hr>'
                        //             }]
                        //     }
                        // },
                        // {
                        //     key: 'droplist',
                        //     type: 'ui-dropfiletable',
                        //     className: 'col-xs-12',
                        //     templateOptions:{
                        //         label:'附件下载列表',
                        //         Restangular:Restangular,
                        //         processInstanceId:'250033',
                        //         ApiService:api_bpm_domain
                        //     }

                        // },
                        // {
                        //     key: 'start_code',
                        //     className:'col-xs-6',
                        //     type: 'ui-hidden'
                        // },
                        // {
                        //     key:'remark',
                        //     type:'ui-textarea',
                        //     className:'col-xs-12',
                        //     templateOptions:{
                        //         label:'remark is ',
                        //         rows:3
                        //     }
                        // },
                        // {
                        //     key:'setStartCode',
                        //     type:'ui-button',
                        //     className:'col-xs-4',
                        //     templateOptions:{
                        //         label:'升级为变更',
                        //         onClick:function(val, options, field, event ,model){
                        //             console.log(options);
                        //             event.preventDefault();
                        //             //model.start_code++;
                        //             //console.log(options);
                        //         }
                        //     }
                        // }
                    ],
                    model: {
                        username: "robin lau",
                        password: "123456",
                        change: { source: { id: 5 } },
                        chkme: false,
                        start_code: 0,
                        arrayData: [{ "id": 13, "dept": "村镇银行管理部" }, { "id": 14, "dept": "电子银行部" }],
                        formtitle: "Hey!I am title value!",
                        name: {
                            first: "robin",
                            last: "lau"
                        },
                        multiselectItem: []
                            //date:"2015-09-15 00:00:00"
                    }
                };
                setTimeout(function() {
                    decodeVMForm(testJson);
                    $scope.$apply();
                }, 500);
                //测试数据结束
            }
        }
        console.log("end decode");
    }
]);